package com.lakeworks.service.api;

import com.alibaba.fastjson2.JSONObject;
import com.lakeworks.common.utils.StringUtils;
import com.lakeworks.domain.SysChannel;
import com.lakeworks.domain.SysChannelAuth;
import com.lakeworks.mapper.SysChannelMapper;
import com.lakeworks.service.ISysChannelAuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

import static org.apache.commons.lang3.StringUtils.isAnyBlank;
import static org.apache.commons.lang3.StringUtils.isNoneBlank;

@Component
public class MerchantMap {

    private static final Logger log = LoggerFactory.getLogger(MerchantMap.class);

    private Map<String, MerchantApiService> map = new ConcurrentHashMap<>();

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private SysChannelMapper sysChannelMapper;

    @Autowired
    private ISysChannelAuthService sysChannelAuthService;

    public Map getMap() {
        return map;
    }

    public MerchantApiService getService(String code) {
        return map.computeIfAbsent(code, this::createService);
    }

    private MerchantApiService createService(String code) {
        SysChannel sysChannel = sysChannelMapper.selectSysChannelByCode(code);
        if (sysChannel != null) {
            MerchantApiType type = sysChannel.getType();
            MerchantApiService service = applicationContext.getBean(type.getImplementation());
            SysChannelAuth sysChannelAuth = sysChannelAuthService.selectByChannelId(sysChannel.getId());
            if(sysChannelAuth != null){
                service.initialize(JSONObject.parseObject(sysChannel.getConfig()),sysChannelAuth.getAk(),sysChannelAuth.getSk());
            }
            return service;
        }
        return null;
    }
}
